/**
 * PageLet资源管理器
 * 1.PageLet模块的注册
 * 2.PageLet模块的显示
 * 3.对PageLet模块css+js资源的加载及缓存
 * 4.对单个或所有PageLet模块的启动
 * 5.对单个或所有PageLet模块的清理
 * @author Finrila | wangzheng4@staff.sina.com.cn
 */
$Import('core.dom.ready');

STK.register("core.util.pageletM", function($) {
    var JSHOST = "http://js.wcdn.cn/t4/";
    var CSSHOST = "http://img.wcdn.cn/t4/";

    if (typeof $CONFIG != "undefined") {
        JSHOST = $CONFIG.jsPath || JSHOST;
        CSSHOST = $CONFIG.cssPath || CSSHOST;
    }
    
    //缓存
    var fileCache = {},//{url:{loaded:true, list:[]}}
 		nowFilterTarget, nsCache = {}, nsThatCache = {};	
	
    /**
     * 在缓存中检查该地址是否已经下载或正在下载
     * 已经下载接回调， 正在下载加入队列 第一次下载需要启动文件下载模块
     * @param {Object} url
     * @param {Object} complete
     * @return {boolean} true/false //是否需要启动文件下载模块
     */
    var checkFileCache = function(url, complete) {
        var _fileObj = fileCache[url] || (fileCache[url] = {
            loaded: false,
            list: []
        });
        if (_fileObj.loaded) {
            complete(url);
            return false;
        }
        _fileObj.list.push(complete);
        if (_fileObj.list.length > 1) {
            return false;
        }
        return true;
    };
    
    /**
     * 从缓存方法列表中回调文件加载完成事件
     * @method callbackFileCacheList
     * @private
     * @param {String} url 文件地址
     */
    var callbackFileCacheList = function(url){
        var cbList = fileCache[url].list;
        for (var i = 0; i < cbList.length; i++) {
            cbList[i](url);
        }
        fileCache[url].loaded = true;
        delete fileCache[url].list;
    };
    
    /**
     * css加载 超时处理30秒为超时时间
     * @method cssLoader
     * @private
     * @param {String} url css地址
     * @param {String} load_ID 约定的css加载检测ID
     * @param {Function} complete 加载完成时的事件回调
     */
    var cssLoader = function(url, load_ID, complete){
        if (!checkFileCache(url, complete)) 
            return;
        var fullUrl = CSSHOST + url;
        //css下载模块
		var link = $.C("link");
		link.setAttribute("rel", "Stylesheet");
		link.setAttribute("type", "text/css");
		link.setAttribute("charset", "utf-8");
		link.setAttribute("href", fullUrl);
		//link.setAttribute("id", "link_" + load_ID);
		
		document.getElementsByTagName("head")[0].appendChild(link);
        
		var load_div = $.C("div");
        load_div.id = load_ID;
        $.core.util.hideContainer.appendChild(load_div);
		
        var _rTime = 3000;//3000*10
        var timer = function() {
            if (parseInt($.core.dom.getStyle(load_div, "height")) == 42) {
                $.core.util.hideContainer.removeChild(load_div);
				callbackFileCacheList(url);
                return;
            }
            if (--_rTime > 0) {
                setTimeout(timer, 10);
            }
            else {
				//callbackFileCacheList(url);
                $.log(url + "timeout!");
                $.core.util.hideContainer.removeChild(load_div);
                //加载失败清除缓存
                delete fileCache[url];
            }
        };
        setTimeout(timer, 50);
    };
    
    /**
     * js加载 超时处理30秒为超时时间
     * @method jsLoader
     * @private
     * @param {String} url js地址
     * @param {Function} complete 加载完成时的事件回调
     */
    var jsLoader = function(url, complete){
        if (!checkFileCache(url, complete)) 
            return;
        var fullUrl = JSHOST + url;
        //js下载模块
        $.core.io.scriptLoader({
            'url': fullUrl,
            onComplete: function(){
                callbackFileCacheList(url);
            },
            onTimeout: function(){
                $.log(url + "timeout!");
                //加载失败清除缓存
                delete fileCache[url];
            }
        });
    };
    
    /**
     * 注册
     * @param {Object} ns
     * @param {Object} fn
     */
    var register = function(ns, fn){
        if (!nsCache[ns]) {
            nsCache[ns] = fn;
        }
    };
    
    /**
     * 启动
     * @param {Object} ns
     */
    var start = function(ns){
        if (ns) {
            if (nsCache[ns]) {
				try {
					nsThatCache[ns] = nsCache[ns]($);
				}catch(e){
					$.log(ns, e);
				}
            } else {
                $.log("start:ns=" + ns + " ,have not been registed");
            }
            return;
        }
        var nsArray = [];
        for (ns in nsCache) {
            nsArray.push(ns);
        }
        $.timedChunk(nsArray, {
            'process': function(ns){
				try {
					nsThatCache[ns] = nsCache[ns]($);
				}catch(e) {
					$.log(ns, e);
				}
            }
        });
    };
    
    /**
     * 显示
     * @param {Object} opts
     * {
     * 	pid:"pl_xxx",//plc的ID属性 必选
     * 	html:"",//将要写到plc的html内容 如果不想替换原plc的内容请不要写该属性(""视为对plc的清空) 可选
     *  js:["xxx.js", "xxx.js"],//plc依赖的js文件的地址列表  可选
     *  css:["xxx.css", "xxx.css"]//plc依赖的css文件的地址列表  可选
     * }
     */
    var view = function(opts){
        var _cssLoadNum = 1, _ns, _box, _html, _css, _js, _cssComplete, _jsComplete;
        
		opts = opts || {};
		
		_html = opts.html;
		_css = opts.css;
        _js = opts.js;
		if(!opts.pid || (!(_box = $.E(opts.pid)) && _html != null)) {
			$.log("node pid["+opts.pid+"] is not on the body")
			return;
		}
		
		if(_js && !$.isArray(_js)) {
			_js = [_js];
		}
        _cssComplete = function() {
            if (--_cssLoadNum > 0) 
                return;
            //css完成 页面渲染
            (typeof _html != "undefined") && (_box.innerHTML = _html);
			if (_js) {
                _jsComplete();
            }
        };
        _jsComplete = function(url){
            if (_js.length > 0) {
                jsLoader(_js.splice(0, 1)[0], _jsComplete);
            }
            if (url && url.indexOf("/pl/") != -1) {
                var _ns = url.replace(/^.*?\/(pl\/.*)\.js\??.*$/, "$1").replace(/\//g, ".");
				start(_ns);
            }
        };
        if (_css) {
            _cssLoadNum += _css.length;
            for (var i = 0, _I; (_I = _css[i]); i++) {
                cssLoader(_I, "js_" + _I.replace(/^\/?(.*)\.css$/i, "$1").replace(/\//g, "_"), _cssComplete);//style\/css\/
            }
        }
        _cssComplete();
    };
    
    /**
     * 清理
     * @param {Object} ns
     */
    var clear = function(ns){ 
        if (ns) {
            if (nsThatCache[ns]) {
				$.log("destroy:"+ ns);
				try {
					nsThatCache[ns].destroy();
				} catch(e) {
					$.log(e);
				}
				delete nsThatCache[ns];
            }
            return;
        }
        for (ns in nsThatCache) {
			$.log("destroy:"+ ns);
			try {
				nsThatCache[ns] && nsThatCache[ns].destroy && nsThatCache[ns].destroy();
			} catch(e) {
				$.log(ns, e);
			}
        }
        nsThatCache = {};
    };
    
    var that = {
        register: register,
        start: start,
        view: view,
        clear: clear,
		destroy: function() {
			that.clear();
			fileCache = {};
			nsThatCache = {};
			nsCache = {};
 			nowFilterTarget = undefined;
		}
    };
	$.core.dom.ready(function() {
		$.addEvent(window, "unload", function() {
			$.removeEvent(window, "unload", arguments.callee);
			that.destroy();
		});
	});
    return that;
});
